package com.eternal.export;

import com.google.common.io.Files;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;

public class CSVUtil {
    public static final String COLUMN_SEPARATOR=",";
    public static final String ROW_SEPARATOR="\r\n";

    private Writer writer;
    private StringBuffer buffer;

    private CSVUtil(String path) throws IOException {
        writer =Files.asCharSink(new File(path), StandardCharsets.UTF_8).openBufferedStream();
        buffer=new StringBuffer();
    }

    public static CSVUtil build(String path) throws IOException {
        return new CSVUtil(path);
    }

    public CSVUtil writeLine(String line) throws IOException {
        writer.append(line).append(ROW_SEPARATOR);
        return this;
    }

    public CSVUtil writeElements(String... elements) throws IOException {
        buffer.setLength(0);
        for(String element:elements){
            buffer.append(element).append(COLUMN_SEPARATOR);
        }
        writeLine(buffer.toString());
        return this;
    }

    public void sync() throws IOException {
        writer.flush();
        writer.close();
    }
}
